import { WebviewWindow } from '@tauri-apps/api/webviewWindow'
import { emit, listen,UnlistenFn } from '@tauri-apps/api/event'
import { PhysicalPosition, LogicalPosition } from '@tauri-apps/api/window'
// import { TrayIcon } from '@tauri-apps/api/tray'
// import { invoke } from '@tauri-apps/api/core'

export const menuBoxWindowWidth = 150
export const menuBoxWindowHeight = 320;//JSON.parse(localStorage.getItem('logged')) ? 320 : 45

export default async function CreateTraymenu() {
    console.log('start create traymenu...')
    
    const initTrayWin = async ()=>{
        const webview = new WebviewWindow("traymenu", {
            url: "/tray/menu",
            title: "消息通知",
            width: menuBoxWindowWidth,
            height: menuBoxWindowHeight,
            skipTaskbar: true,
            decorations: false,
            center: false,
            resizable: false,
            alwaysOnTop: true,
            focus: true,
            x: window.screen.width + 50,
            y: window.screen.height + 50,
            visible: false
        })
    
        // 托盘消息事件
        await webview.listen('tauri://window-created', async () => {
            console.log('traymenu create')
        })
        await webview.listen('tauri://blur', async () => {
            console.log('traymenu blur')
            const win: WebviewWindow | null = await WebviewWindow.getByLabel('traymenu')
            await win?.hide()
        })
        await webview.listen('tauri://error', async(error) => {
            console.log('traymenu error!', error)
        })
    }

    initTrayWin()
    // 监听托盘事件
    const trayEnterListen: Promise<UnlistenFn> = listen('tray_contextmenu', async (event) => {
        console.log(event)

        const win = await WebviewWindow.getByLabel('traymenu')
        if(!win) return
        

        const position: any = event.payload
        if(win) {
            await win.setAlwaysOnTop(true)
            await win.setFocus()
            await win.setPosition(new LogicalPosition(position?.x, position?.y - menuBoxWindowHeight))
            await win.show()
        }
    })
}